package mapevents;

import enumm.GROUND;
import gameengine.map.Field;
import gameengine.map.FireRange;
import gameengine.map.Map;
import gameengine.map.unit.Unit;

public final class MapFireRangeSelection extends AbstractMapEvent {
    private final transient Unit unit;
    private final transient int xStart;
    private final transient int yStart;

    public MapFireRangeSelection(final int xCoordinate, final int yCoordinate, final Unit selectedUnit) {
        super();
        this.unit = selectedUnit;
        this.xStart = xCoordinate;
        this.yStart = yCoordinate;
    }

    @Override
    public Unit getAttacker() {
        return unit;
    }

    @Override
    public MAPEVENTTYPE getType() {
        return MAPEVENTTYPE.FIRERANGE;
    }

    @Override
    public Unit getUnit() {
        return unit;
    }

    @Override
    public int getXStart() {
        return xStart;
    }

    @Override
    public int getXTarget() {
        return 0;
    }

    @Override
    public int getYStart() {
        return yStart;
    }

    @Override
    public int getYTarget() {
        return 0;
    }

    @Override
    public AbstractMapEvent newMapEvent(final int xClick, final int yClick, final boolean leftClick, final Map map, final int party) {
        final Field field = map.getField(xClick, yClick);
        final Unit tmpUnit = field.getUnit();

        AbstractMapEvent returnVal;

        if (tmpUnit == null) {
            if (field.getGround() == GROUND.BUILDING) {
                returnVal = new BuildingEvent(xClick, yClick);
            } else {
                returnVal = new MapDeSelection(xClick, yClick, tmpUnit);
            }
        } else {
            AbstractMapEvent event = new MapSelection(xClick, yClick, tmpUnit);
            if (leftClick) {
                event = new MapSelection(xClick, yClick, tmpUnit);
            } else {
                if (xClick == xStart && yClick == yStart) {
                    returnVal = new MapDeSelection(xClick, yClick, tmpUnit);
                } else {
                    returnVal = new MapSelection(xClick, yClick, tmpUnit);
                }
            }
            if (tmpUnit.getParty() == party) {
                returnVal = event;
            } else {
                if (new FireRange(xStart, yStart, map).getField(xClick, yClick) && tmpUnit.canAttack()) {
                    returnVal = new MapAttackEvent(this, event);
                } else {
                    returnVal = new MapDeSelection(xClick, yClick, tmpUnit);
                }
            }
        }

        return returnVal;
    }
}
